import { Spin } from 'antd';
import { FC, useMemo, useState, useRef, useEffect } from "react";
// https://github.com/DLTech21/ofd.js
export interface OfdViewProps {
  fileUrl: string;
  height?: number | string;
}

const OfdView: FC<OfdViewProps> = ({ fileUrl, height }) => {
  const divRef = useRef<HTMLDivElement>(null);
  const [spinning, setSpinning] = useState<boolean>(false);

  useEffect(() => {
    if (fileUrl) {
      setSpinning(true);
      // @ts-ignore
      import('./lib/ofd.umd.min').then(({ parseOfdDocument, renderOfd }) => {
        parseOfdDocument({
          ofd: fileUrl,
          success(res: any) {
            setSpinning(false);
            const result = res[0];
            const ofdDoms = renderOfd(divRef.current?.getBoundingClientRect?.()?.width, result);
            ;(divRef.current as HTMLDivElement).innerHTML = '';
            ofdDoms.forEach((div: Node) => {
                divRef.current?.appendChild(div);
            });
          },
          fail(error: unknown) {
            setSpinning(false);
            (divRef.current as HTMLDivElement).innerHTML = `解析失败${error}`;
            console.log(error, 'ofd格式解析失败');
          },
        });
      });
    }
  }, [fileUrl]);

  return (
    <Spin spinning={spinning}>
    <div
      style={{
        height,
        overflowY: "auto",
        textAlign: 'center'
      }}
      ref={divRef}
    >
      {/* <Spin style={{margin: '30px auto'}} size="small" spinning={spinning} /> */}
      {/* <div ></div> */}
    </div>
    </Spin>
  );
};

export default OfdView;
